export const maxTenThousand = (num) => {
  let mathNUms = 0;
  if (num) {
    if (Number(num) >= 10000) {
      mathNUms = (Number(num) / 10000).toFixed(2);
    } else {
      mathNUms = num;
    }
  }
  return mathNUms;
};

/**
 * 保存阅读记录到本地
 * @param {Object} readPageInfo - 阅读记录对象
 * @param {string} readPageInfo.courseId - 书籍ID
 * @param {string} readPageInfo.index - 章节index
 * @param {string} readPageInfo.pageIndex - 页码
 *  @param {string} readPageInfo.courseDetailsId - 章节id
 */
export const saveReadRecord = (readPageInfo) => {
  const MAX_RECORDS = 1000; // 最多存储1000条记录
  const history = localStorage.getItem("readHistory")
    ? JSON.parse(localStorage.getItem("readHistory"))
    : {};

  // 如果记录超过限制，删除最旧的一条
  const keys = Object.keys(history);
  if (keys.length >= MAX_RECORDS) {
    let oldestKey = keys[0];
    let oldestTime = history[oldestKey].updateTime;

    keys.forEach((key) => {
      if (history[key].updateTime < oldestTime) {
        oldestKey = key;
        oldestTime = history[key].updateTime;
      }
    });
    delete history[oldestKey];
  }

  // 存储新记录
  history[readPageInfo.courseId] = {
    index: readPageInfo.index,
    pageIndex: readPageInfo.pageIndex,
    updateTime: new Date().getTime(),
    courseDetailsId: readPageInfo.courseDetailsId,
    courseId: readPageInfo.courseId,
  };
  localStorage.setItem("readHistory", JSON.stringify(history));
};

/**
 * 获取某本书的阅读记录
 * @param {string} courseId - 书籍ID
 * @return {Object|null} 返回阅读记录（包含 index, pageIndex, updateTime），如果没有则返回 null
 */
export const getReadRecord = (courseId) => {
  try {
    const history = localStorage.getItem("readHistory")
      ? JSON.parse(localStorage.getItem("readHistory"))
      : {};
    return history[courseId] || {};
  } catch (e) {
    console.error("获取阅读记录失败", e);
    return {};
  }
};

/**
 * 清空某本书的记录
 */
export const clearReadRecord = (courseId) => {
  const history = localStorage.getItem("readHistory")
    ? JSON.parse(localStorage.getItem("readHistory"))
    : {};
  if (courseId) {
    delete history[courseId];
    localStorage.setItem("readHistory", JSON.stringify(history));
  } else {
    localStorage.setItem("readHistory", "");
  }
};

/**
 * 显示开屏广告
 */
export const showAd = () => {
  uni.reLaunch({
    url: "/pages/ad/index",
  });
};

export const hoursDifference = (timestamp1, timestamp2) => {
  // 计算时间差的绝对值（毫秒）
  const diff = Math.abs(timestamp1 - timestamp2);

  const twentyFourHours = 24 * 7 * 60 * 60 * 1000; // 86400000

  // 判断时间差是否大于等于twentyFourHours小时
  return diff >= twentyFourHours;
};
